import { Injectable } from '@angular/core';
import { apiList } from '../../@shared/http/apiList';
import { HttpClient } from '@angular/common/http';
import { UserInfo } from '../../@shared/models/userinfo';
import { Result } from '../../@shared/models/result';
import { finalize, Observable, of } from 'rxjs';
import { Menu } from '../../@shared/models/menu';
import { MenuStoreService } from './menu-store.service';
import { resolve } from '@angular/compiler-cli';
import { fnFlatDataHasParentToTree } from '../../utils/treeTableTools';

@Injectable()
export class AuthService {
  constructor(
    public http: HttpClient,
    public api: apiList,
    public menuService: MenuStoreService) {
    console.log(this.api)
  }

  login(account: string, password: string) {
    let url = this.api.baseurl + this.api.urlList.login.path;
    return this.http.post<Result<UserInfo>>(url ,{loginId: account, password: password});
  }
  loginIn(userInfo: UserInfo): Promise<void> {
    return new Promise(resolve => {
      localStorage.setItem(userInfo.tokenName, userInfo.tokenValue);
      localStorage.setItem('userinfo', JSON.stringify(userInfo));
      this.getMenuByUserId(userInfo.loginId).pipe(
          finalize(() => {
            resolve();
          })
        ).subscribe(
      res => {
          let menus = res.data.filter(item => {
          return item.menuType === 'C';
          });
          const temp = fnFlatDataHasParentToTree(menus);
          // 存储menu
          this.menuService.setMenuArrayStore(temp);
          resolve();
        }
    );
    });
  }

  logout() {
    localStorage.removeItem('access_token');
    localStorage.removeItem('userinfo');
    this.menuService.setMenuArrayStore([]);
  }

  setSession(userInfo: UserInfo) {
    localStorage.setItem(userInfo.tokenName, userInfo.tokenValue);
    localStorage.setItem('userinfo', JSON.stringify(userInfo));
  }

  isUserLoggedIn() {
    if (localStorage.getItem('userinfo')) {
      return true;
    } else {
      return false;
    }
  }

  public getMenuByUserId(loginId: string) {
    return this.http.get<Result<Menu[]>>(this.api.baseurl + `/menu/${loginId}`);
  }

  public getMenuByToken() {
    return this.http.get<Result<Menu[]>>(this.api.baseurl + '/menu/token');
  }
}
